package common

import (
	"errors"
	"fmt"
	"strconv"
	"strings"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

var jwtKey = []byte("fdfdsfdsfdsafdsafsdafa")

type JwtClaims struct {
	Role string `json:"role,omitempty"`
	jwt.RegisteredClaims
}

func GenerateToken(id int64, roles []string) (string, error) {
	claims := JwtClaims{
		Role: strings.Join(roles, ","),
		RegisteredClaims: jwt.RegisteredClaims{
			Subject:   strconv.FormatInt(id, 10),
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 24)),
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(jwtKey)
}

func VerifyToken(tokenStr string) (*JwtClaims, error) {
	var jwtClaims JwtClaims
	token, err := jwt.ParseWithClaims(tokenStr, &jwtClaims, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return jwtKey, nil
	})
	if err != nil {
		return nil, err
	}
	if token.Valid {
		return &jwtClaims, nil
	}
	return nil, errors.New("invalid token")
}
